import {
	observable,
	action,
	computed
} from 'mobx';
import {
	Tools,
	Bubble,
	Toast,
	Modal,
} from "weaver-mobile";
import {
	Form
} from 'weaver-mobile-page';
import {isEmpty,forEach} from 'lodash';
import * as api from '../../apis/personInfo';
const getLabel = Tools.getLabel;
const alert = Modal.alert;

class PersonInfoStore {
	basicOtherParams = {};
	personalOtherParams = {};
	portraitBase64 = '';
	pictureBase64 = '';

	@observable isPageInit = false;

	@observable selectedKey = 0;
	@observable hasSave = false; //是否可以保存
	@observable basicConditions = []; 
	@observable personalConditions = [];

	@observable basicForm = new Form.Store({
		route: '/personalInfo'
	});
	@observable personalForm = new Form.Store({
		route: '/personalInfo'
	});

	@observable pictureUrl = ''; //照片链接
	@observable portraitName = ''; //头像对应人员名称
	@observable portraitUrl = ''; //头像链接
	@observable uploadPortrailAuth = false; //有无上传头像的权限

	@computed get tabDatas() {
		const datas = [];
		if (this.isBasicInfoHasEditElement) {
			datas.push({
				title: getLabel(505832, '基本信息'),
			});
		}
		if (this.isPersonalInfoHasEditElement) {
			datas.push({
				title: getLabel(505833, '个人信息'),
			});
		}
		return datas;
	}

	//页面是否包含头像栏目
	@computed get hasProtraitRow() {
		return this.uploadPortrailAuth;
	}

	//页面是否包含照片栏目
	@computed get hasPictureRow() {
		return this.basicConditions.some(c => c.hasResourceImage);
	}

	//照片栏目是否存在图片
	@computed get hasPicture() {
		//选择图片后
		if (this.pictureUrl) {
			return true;
		}

		let pictureItem;
		//初始化时，根据item中value值判断是否存在照片。
		this.basicConditions.forEach(c => c.items.forEach(item => {
			if (item.domkey[0] === 'resourceimageid') {
				pictureItem = item;
			}
		}));

		if (pictureItem) {
			return pictureItem.value
		}
	}

	//判断protraitUrl是否为base64格式
	@computed get isProtraitUrlBase64() {
		const firstChar = this.portraitUrl[0];

		if (firstChar !== '/') {
			return true;
		}
	}

	@computed get isPictureUrlBase64(){
		if (this.pictureUrl) {
			const firstChar = this.pictureUrl[0];

			if (firstChar !== '/') {
				return true;
			}
		}

	}

	//获取【基本信息】在conditions中索引值
	@computed get basicInfoIndex() {
		const index = this.basicConditions.findIndex(c => c.hasResourceImage !== undefined);

		return (index > 0) ? index : 0;
	}

	//【基本信息】是否有可编辑元素
	@computed get isBasicInfoHasEditElement() {
		let length = 0;

		if (this.hasProtrait) {
			length = length + 1;
		}

		length += this.calculateEditableItems(this.basicConditions);

		return length > 0
	}

	//【个人信息】是否有可编辑元素
	@computed get isPersonalInfoHasEditElement() {
		let length = 0;

		length += this.calculateEditableItems(this.personalConditions);

		return length > 0;
	}

	//判断是否有可编辑的表单元素
	@computed get hasEditableFormElement() {
		return [this.isBasicInfoHasEditElement, this.isPersonalInfoHasEditElement].some(bool => bool);
	}

	//计算conditions包含可编辑表单元素的个数
	calculateEditableItems = (conditions) => {
		let length = 0;
		conditions.forEach(c => {
			const showItems = c.items.filter(item => {
				if (
					(item.otherParams && item.otherParams.hide) ||
					(!item.otherParams && item.hide)
				) {
					return false
				}
				return true;
			})

			length += showItems.length;
		});
		return length;
	}

	init = () => {
		this.loadingToast();

		this.isPageInit = false;

		this.getBasicForm().then(() => { 
			this.getPersonalForm().then( () => {
				this.getPortraitInfo().then(() => { //获取头像信息
					this.isPageInit = true;
					this.getUploadPortrailAuthInfo(); //获取头像上传权限的信息
				})
			})
		});
	}

	@action getBasicForm = () => {
		return new Promise((resolve, reject) => {
			const params = {
				viewattr: 2,
				operation:'getResourceBaseView'
			};

			api.getResourceCard(params).then(datas => {
				const {
					result,
				} = datas, {
					conditions,
				} = result;

				this.storeSaveParams(result,"basic");
				this.initForm(conditions,"basic");
				this.setPictureUrl(conditions);

				resolve();
			});
		})
	}

	@action getPersonalForm = () => {
		return new Promise((resolve, reject) => {
			const params = {
				viewAttr: 2,
				operation: "getResourcePesonalView",
				id: this.basicOtherParams.id,
			};

			api.getResourceCard(params).then(datas => {
				const {
					result,
				} = datas, {
					conditions = [],
					tables,
				} = result;

				this.storeSaveParams(result,"personal");
				this.initForm(conditions,"personal");
				this.tableInfo = tables;

				resolve();
			});
		})
	}

	//获取头像信息
	@action getPortraitInfo = () => {
		return new Promise((resolve, reject) => {
			const params = {
				isMobx: 1
			};
			api.getResourceBaseTitle(params).then(datas => {
				const {
					lastname,
					messagerurl,
				} = datas.result;

				this.portraitName = lastname;
				this.portraitUrl = messagerurl;
				this.hideToast();

				resolve();
			})
		})
	}

	//获取能否上传头像的权限
	getUploadPortrailAuthInfo = () => {
		const params = {
			userId: this.basicOtherParams.id,
		};

		api.getUploadPortrailAuthInfo(params).then(datas => {
			this.uploadPortrailAuth = datas.hasRight;
		})
	}

	save = () => {
		this.checkHrmResourceFields().then(() => {
			if (this.isProtraitUrlBase64) { //重新上传过头像
				this.saveProtrait().then(() => {
					this.saveForm()
				})
			} else {
				this.saveForm()
			}
		})
	}

	saveForm = () => {
		this.saveBasicForm().then(() => {
			if (this.isPersonalInfoHasEditElement) {
				this.loadingToast();
				this.savePersonalForm().then(() => {
					this.callEmobileAPI();
				}).finally(() => this.hideToast())
			} else {
				this.callEmobileAPI();
			}
		}).finally(() => this.hideToast())
	}

	callEmobileAPI = () => {
		this.refreshUserInfo().then(() => {
			this.closeWindow();
		});
	}

	saveProtrait = () => {
		return new Promise((resolve, reject) => {
			const params = {
				userId: this.basicOtherParams.id,
				imageDataUrl: this.portraitUrl
			};

			api.saveUserIcon(params).then(datas => {
				const {
					status,
					message,
				} = datas;

				if (status === '1') {
					resolve();
				}else{
					Bubble.error(message);
					reject();
				}
			})
		})
	}

	saveBasicForm = () => {
		return new Promise((resolve, reject) => {
			this.setNoNeedValidateFormFields();

			this.basicForm.doValidate(msg => {
				const {
					pass,
					message
				} = msg;

				if (pass) {
					this.checkFieldPattern().then(()=>{
						const params = {
							...this.basicForm.formParams,
							...this.basicOtherParams
						};
						//修改过照片
						if (this.isPictureUrlBase64) {
							Object.assign(params, {
								resourceimageBase64: this.pictureUrl,
							});
						}

						this.loadingToast();

						api.editResource(params).then(datas => {
							const {
								status,
								message
							} = datas;

							if (status === '1') {
								if (!this.isPersonalInfoHasEditElement) {
									Bubble.success(getLabel(83551, '保存成功！'));
								}
								resolve();
							} else {
								Bubble.error(message);
								reject();
							}
						})
					}).catch(() => reject())
				}else{
					Bubble.warning(message);
					reject();
				}
			})
		})
	}

	getTableEditParams = () => {
		const params = {};
		this.tableInfo && this.tableInfo.forEach(t => {
			t.tabinfo.datas = t.tabinfo.datas || [];
			params[t.tabinfo.rownum] = t.tabinfo.datas.length;
			t.tabinfo && t.tabinfo.datas && t.tabinfo.datas.forEach((item, index) => {
				!isEmpty(item) && forEach(item, (value, key) => {
					Object.assign(params, {
						[`${key}_${index}`]: value
					});
				})
			})
		})
		return params;
	}

	savePersonalForm = () => {
		return new Promise( (resolve, reject) => {
			this.personalForm.doValidate(msg => {
				const {
					pass,
					message
				} = msg;

				if (pass) {
					const params = {
						...this.personalForm.formParams,
						...this.getTableEditParams(),
						...this.personalOtherParams,
					};
					api.editResource(params).then(datas => {
						const {
							status,
							message
						} = datas;

						if (status === '1') {
							Bubble.success(getLabel(83551, '保存成功！'));
							resolve();
						} else {
							Bubble.error(message);
							reject();
						}
					})
				}else{
					Bubble.warning(message);
					reject();
				}
			})
		} )
	}

	setNoNeedValidateFormFields = () => {
		const {
			accounttype
		} = this.basicForm.formParams;

		this.basicForm.conditioninfo.map(c => c.items.map(item => {
			const {
				domkey,
				viewAttr,
			} = item;

			if (domkey[0] === 'belongto' && viewAttr === 3) {
				Object.assign(item, {
					rules: (accounttype === '1') ? 'required|string' : ''
				})
			}
			if (domkey[0] === 'resourceimageid' && this.pictureUrl) {
				Object.assign(item, {
					rules: ''
				})
			}
		}))
	}

	checkHrmResourceFields = () => {
		return new Promise((resolve, reject) => {
			const {
				lastname,
				workcode,
				managerid
			} = this.basicForm.formParams;

			const params = {
				id: this.basicOtherParams.id,
				lastname,
				workcode,
				managerid,
			};

			api.hrmResourceCheck(params).then(datas => {
				const {
					status,
					message,
					messagetype,
				} = datas;

				if (status === '1') {
					resolve();
				} else {
					if (messagetype === 'confirm') {
						this.showConfirm(message).then(()=>{
							resolve();
						}).catch(() => reject())
					}else{
						Bubble.warning(message);
						reject();
					}
				}
			})
		})
	}

	checkFieldPattern = () => {
		return new Promise((resolve, reject) => {
			const {
				email,
				managerid,
			} = this.basicForm.formParams;
			const regExp = /^(?:[a-z\d]+[&\_\-\+\.]?)*[a-z\d]+@(?:([a-z\d]+\-?)*[a-z\d]+\.)+([a-z]{2,})+$/i;
			
			if (this.showFormFields.includes('email') && email && !regExp.test(email)) {
				Bubble.warning(getLabel(388157, '邮箱格式不正确'));
				reject();
				return;
			}
			
			if(this.showFormFields.includes('managerid') && !managerid){
				this.showConfirm(getLabel(16072,'此员工还没有输入直接上级，确定不输入吗？')).then(()=>{
					resolve();
				}).catch(() => reject())
				return;
			}
			
			resolve();
		})
	}

	showConfirm = (msg) => {
		return new Promise((resolve, reject) => {
			alert(getLabel(384132, '系统提示'), msg, [{
				text: getLabel(506972, '取消'),
				onPress: () => reject(),
				style: 'default'
			}, {
				text: getLabel(16634, '确认'),
				onPress: () => resolve(),
			}, ])
		})
	}

	refreshUserInfo = () => {
		return new Promise( (resolve,reject)=>{
			if (window.em && window.em.checkJsApi('refreshUserInfo')) {
				window.em.refreshUserInfo({
					sysId: window.localStorage.emobile_ec_id,
					userId: this.basicOtherParams.id,
					success:() => resolve(),
					fail: errorMsg => {
						Bubble.error(JSON.stringify(errorMsg));
						reject();
					}
				});
			}
		} )
	}
	//存储除了表单参数以外，保存时需要传入的其他参数
	storeSaveParams = (result, type) => {
		['editcontact', 'id'].forEach(val => {
			if (result[val]) {
				this[`${type}OtherParams`][val] = result[val];
			}
		});
		Object.assign(this[`${type}OtherParams`], {
			operation: (type === "basic") ? 'editresourcebasicinfo' : 'editpersonalinfo',
		});
		
	}

	initForm = (conditions, type) => {
		if (type === "basic") {
			this.collectShowFormFields(conditions);
			this.basicConditions = conditions;
			this.basicForm.initForm(conditions, '/personalInfo');
		}else{
			this.personalConditions = conditions;
			this.personalForm.initForm(conditions, '/personalInfo');
		}
	}

	collectShowFormFields = (conditions) => {
		this.showFormFields = [];//重置showFormFields

		conditions && conditions.forEach(c => c.items.forEach(item => {
			const {
				otherParams,
				domkey
			} = item;

			if (
				!otherParams ||
				(otherParams && !otherParams.hide)
			) {
				this.showFormFields.push(domkey[0]);
			}
		}))
	}

	//设置照片的链接
	setPictureUrl = (conditions) => {
		conditions.forEach(c => c.items.forEach(item => {
			if (item.domkey[0] === 'resourceimageid' && item.value) {
				this.pictureUrl = `/weaver/weaver.file.FileDownload?fileid=${item.value}`;
			}
		}))
	}

	//点击照片触发的回调函数
	handlePictureClick = () => {
		this.uploadImage('picture');
	}

	//点击头像触发的回调函数
	handlePortraitClick = () => {
		this.uploadImage('portrait');
	}

	//上传图片，包含两个步骤：选择和上传。
	uploadImage = (type) => {
		if (window.em && window.em.checkJsApi('chooseImage') && window.em.checkJsApi('getLocalImgData')) {
			window.em.chooseImage({
				count: 1,
				isCrop: (type === 'portrait') ? true : false,
				sourceType: ['album', 'camera'],
				success: (res) => {
					window.em.getLocalImgData({
						localId: res.localIds[0],
						success: (res) => {
							const base64 = `data:image/png;base64,${res.localData}`;

							this[`${type}Base64`] = base64;
							this[`${type}Url`] = base64;

							if (type === "picture" &&  ['/messager/images/icon_m_wev8.jpg', '/messager/images/icon_w_wev8.jpg'].includes(this.portraitUrl)) {
								this.portraitUrl = base64; //头像为默认图片时，使用照片作为头像
							}
						},
						fail: (msg)=> {
							Bubble.error(JSON.stringify(msg))
						}
					});
				}
			});
		}
	}

	closeWindow = () => {
		if (!window.em) {
			return ;
		}
		if (window.em.checkJsApi('closeAndReload')) {
			window.em.closeAndReload({
				fail: (msg) => {
					Bubble.error(JSON.stringify(msg))
				}
			});
			return ;
		}
		if (window.em.checkJsApi('closeWindow')) {
			window.em.closeWindow({
				fail: (msg) => {
					Bubble.error(JSON.stringify(msg))
				}
			});
		}
	}

	@action handleTabClick = (data, key) =>{
		this.selectedKey = key;
	}

	loadingToast = () => {
		Toast.loading('', 0);
	}

	hideToast = () => {
		Toast.hide()
	}



}

export const personInfoStore = new PersonInfoStore();